﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Ebiz.libs;
using System.Globalization;
using System.Web.Services;
using System.Web.Script.Services;
using System.Text;

namespace Ebiz
{
    public partial class MyAccount : System.Web.UI.Page
    {
        public Dictionary<string, string> ViewData = new Dictionary<string, string>();
        protected void Page_Load(object sender, EventArgs e)
        {
            string UserName = Func.GetUserInfo(Func.ShowInfo._UserID);
            string FullName = Func.GetUserInfo(Func.ShowInfo._FullName);

            ViewData.Add("UserID", UserName);
            ViewData.Add("FullName", FullName);

            List<string> lstData = LoadData(UserName);
            ViewData.Add("Email", lstData[0]);
            ViewData.Add("Role", lstData[2]);
            ViewData.Add("NetID", lstData[3]);

            
            string[] lstDate = (lstData[4]).Split(' ');
            string _sDate = Func.FormatDate(lstDate[0], Func.DTFormat.MDYtoDMY, "/", "-");
            string _sTime = lstDate[1];
            string LogDate = _sDate + " " + _sTime;

            ViewData.Add("LastLogin", LogDate);
            ViewData.Add("LastIPAddress", lstData[5]);

            string AppRole = lstData[6];
            string optRole = "";
            switch (AppRole) { 
                case "N":
                    ViewData.Add("AppRole", "No");

                    optRole = "<option value=\"N\" selected>No</option>";
                    optRole += "<option value=\"Y\">Yes</option>";
                    ViewData.Add("AppOptRole", optRole);

                    break;
                case "Y":
                    ViewData.Add("AppRole", "Yes");

                    optRole = "<option value=\"N\">No</option>";
                    optRole += "<option value=\"Y\" selected>Yes</option>";
                    ViewData.Add("AppOptRole", optRole);

                    break;
            }
        }

        private static List<string> LoadData(string UserID){
            List<string> result = new List<string>();

            string dbName = DBUtilities.GetDBName("devCon");
            //string qry = "SELECT UserAccounts.Email, UserAccounts.IDRole, " +
            //    "mstRole.RoleName, UserAccounts.IDNetwork, UserAccounts.LastLog, UserAccounts.LastIP, " +
            //    "(CASE WHEN (UserAccounts.AppActor = 'Y') THEN '1' ELSE '0' END) AS AppRole " +
            //    "FROM Ebiz.dbo.UserAccounts INNER JOIN " +
            //    "Ebiz.dbo.mstRole ON mstRole.IDRole = UserAccounts.IDRole " +
            //    "WHERE (UserAccounts.UserName = @UserName)";
            string qry = "SELECT UserAccounts.Email, UserAccounts.IDRole, " +
                "mstRole.RoleName, UserAccounts.IDNetwork, UserAccounts.LastLog, UserAccounts.LastIP, " +
                "UserAccounts.AppActor AS AppRole " +
                "FROM " + dbName + ".dbo.UserAccounts INNER JOIN " + dbName + 
                ".dbo.mstRole ON mstRole.IDRole = UserAccounts.IDRole " +
                "WHERE (UserAccounts.UserName = @UserName)";
            SqlConnection cn = new SqlConnection(DBUtilities.strConnection("devCon"));
            using (cn) {
                try{
                    cn.Open();
                    SqlCommand cmd = new SqlCommand(qry, cn);
                    cmd.Parameters.AddWithValue("@UserName", UserID);
                    SqlDataReader rdr = cmd.ExecuteReader();
                    if (rdr.HasRows) {
                        if (rdr.Read()) {
                            for (int idx = 0; idx < 7; idx++){
                                result.Add(rdr.GetValue(idx).ToString());
                            }
                        }
                    }
                }catch (Exception ex){
                    string errMsg = ex.Message;
                }finally{
                    if (cn.State == ConnectionState.Open) {
                        cn.Close();
                    }
                }                
            }
            return result;
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<object> ChangePassword(string OldPassword, string NewPassword,
            string NewPasswordExt) {

            string dbName = DBUtilities.GetDBName("devCon");
            List<object> result = new List<object>();

            if (string.IsNullOrEmpty(OldPassword)){
                result.Add(0);
                result.Add("Old Password must be filled");
            }else if(string.IsNullOrEmpty(NewPassword)){
                result.Add(0);
                result.Add("New Password must be filled");
            }else if (string.IsNullOrEmpty(NewPasswordExt)){
                result.Add(0);
                result.Add("Re-Type Password must be filled");
            }else {
                int PwdLen1 = Func.strlen(NewPassword);
                int PwdLen2 = Func.strlen(NewPasswordExt);
                if (PwdLen1 < 4 || PwdLen1 > 16) {
                    result.Add(0);
                    result.Add("Password between 4 - 16 characters");
                }else if (PwdLen2 < 4 || PwdLen2 > 16){
                    result.Add(0);
                    result.Add("Password between 4 - 16 characters");
                }else{
                    if (!(NewPassword == NewPasswordExt)){
                        result.Add(0);
                        result.Add("Passwords does not match");
                    }else{
                        string UserName = Func.GetUserInfo(Func.ShowInfo._UserID);
                        string Password = cryptMD5.MD5Hash(OldPassword);
                        string NewPwd = cryptMD5.MD5Hash(NewPassword);
                        if (IsValid_Password(UserName, Password) == true){
                            string qry = "UPDATE " + dbName + ".dbo.UserAccounts SET Password = @Password WHERE " +
                                "(UserName = @UserName)";
                            SqlConnection cn = new SqlConnection(DBUtilities.strConnection("devCon"));
                            using (cn){
                                try{
                                    cn.Open();
                                    SqlCommand cmd = new SqlCommand(qry, cn);
                                    cmd.Parameters.AddWithValue("@Password", NewPwd);
                                    cmd.Parameters.AddWithValue("@UserName", UserName);
                                    if (cmd.ExecuteNonQuery() > 0){
                                        result.Add(1);
                                        result.Add("Password has successfully changed");
                                    }else{
                                        result.Add(0);
                                        result.Add("Your request can not be proccessed at the moment.<br />Please try again later.");
                                    }
                                }catch (Exception ex){
                                    string errMsg = ex.Message;
                                    result.Add(0);
                                    result.Add(errMsg);
                                }finally{
                                    if (cn.State == ConnectionState.Open){
                                        cn.Close();
                                    }
                                }
                            }
                        }else{
                            result.Add(0);
                            result.Add("Your request can not be proccessed at the moment.<br />Please try again later.");
                        }
                    }
                }
            }
            return result;
        }

        private static bool IsValid_Password(string UserName, string Password) {
            bool result = false;

            string dbName = DBUtilities.GetDBName("devCon");
            string OldPassword = Password;
            string qry_check = "SELECT COUNT(UserName) FROM " + dbName + ".dbo.UserAccounts WHERE " +
                "(UserName = @UserName) AND (Password = @Password)";

            SqlConnection cn = new SqlConnection(DBUtilities.strConnection("devCon"));
            using (cn){
                try{
                    cn.Open();
                    SqlCommand cmd = new SqlCommand(qry_check, cn);
                    cmd.Parameters.AddWithValue("@UserName", UserName);
                    cmd.Parameters.AddWithValue("@Password", OldPassword);
                    SqlDataReader rdr = cmd.ExecuteReader();
                    if (rdr.HasRows) {
                        if (rdr.Read()) {
                            int tmpResult = Convert.ToInt32(rdr.GetValue(0));
                            if (tmpResult > 0) {
                                result = true;
                            }
                        }
                    }
                }catch (Exception ex){
                    string errMsg = ex.Message;
                    result = false;
                }finally{
                    if (cn.State == ConnectionState.Open){
                        cn.Close();
                    }
                }
            }
            return result;
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<object> ChangeEmail(string EmailAddress) {
            List<object> result = new List<object>();
            string UserName = Func.GetUserInfo(Func.ShowInfo._UserID);
            string qry = "UPDATE UserAccounts SET Email = @Email WHERE " +
                "(UserName = @UserName)";
            SqlConnection cn = new SqlConnection(DBUtilities.strConnection("devCon"));
            using (cn) {
                try {
                    cn.Open();
                    SqlCommand cmd = new SqlCommand(qry, cn);
                    cmd.Parameters.AddWithValue("@UserName", UserName);
                    cmd.Parameters.AddWithValue("@Email", EmailAddress);
                    if (cmd.ExecuteNonQuery() > 0){
                        result.Add(1);
                        result.Add("Update Success");
                    }else{
                        result.Add(0);
                        result.Add("Update Failed");
                    }
                }
                catch (Exception ex) {
                    string errMsg = ex.Message;
                }
                finally {
                    if (cn.State == ConnectionState.Open) {
                        cn.Close();
                    }
                }
            }

            return result;
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<object> ChangeAvailability(string Availability) {
            List<object> result = new List<object>();
            string UserName = Func.GetUserInfo(Func.ShowInfo._UserID);
            string qry = "UPDATE UserAccounts SET AppActor = @AppActor WHERE " +
                "(UserName = @UserName)";
            SqlConnection cn = new SqlConnection(DBUtilities.strConnection("devCon"));
            using (cn){
                try{
                    cn.Open();
                    SqlCommand cmd = new SqlCommand(qry, cn);
                    cmd.Parameters.AddWithValue("@UserName", UserName);
                    cmd.Parameters.AddWithValue("@AppActor", Availability);
                    if (cmd.ExecuteNonQuery() > 0){
                        result.Add(1);
                        result.Add("Update Success");
                    }
                    else{
                        result.Add(0);
                        result.Add("Update Failed");
                    }
                }catch (Exception ex){
                    string errMsg = ex.Message;
                }finally{
                    if (cn.State == ConnectionState.Open){
                        cn.Close();
                    }
                }
            }
            return result;
        }
    }
}
